import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.Socket;

class ClientWorker extends Thread {
	private Socket client;
	int bytesRead;
	int current = 0;

	// Constructor
	ClientWorker(Socket client) {
		this.client = client;
	}

	public void run() {
		try {
			ObjectInputStream ois = new ObjectInputStream(client
					.getInputStream());
			P2PPackage data = (P2PPackage) ois.readObject();

			synchronized (Module.getScreen()) {
				Module.writeToScreen("Receiving a file from: "
						+ client.getInetAddress());
				Module.writeToScreen("File name: " + data.getFileName());
				Module.writeToScreen("File size: "
						+ (float) data.getData().length / 1024 + " Mb");
			}
			FileOutputStream fos = new FileOutputStream(data.getFileName());
			fos.write(data.getData());
			synchronized (Module.getScreen()) {
				Module.writeToScreen(data.getFileName() + " is received.");
				Module.writeToScreen("\n");
			}
			PrintWriter out = new PrintWriter(client.getOutputStream(), true);
			out.println("File received successfully");
			out.close();
			fos.close();
			ois.close();
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}